#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib
import urllib2
import re
import ToolUtil
import os

class BeautifulGirl:
#初始化页面
    def __init__(self):
        self.siteUrl = 'http://www.mzitu.com/all'
        self.header =  {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}
        self.tool = ToolUtil.ToolUtil()
        # 判断是否是当前目录,默认是当前路径
        self.dirLocal = os.path.abspath(os.path.dirname('BeautifulGirl.py'))
    #获取索引页面的内容
    def getPage(self,url):
        request = urllib2.Request(url,headers=self.header)
        response = urllib2.urlopen(request)
        content = response.read().decode('utf-8')
        return content
    #获取各年份下的所有链接
    def getUrlOfYear(self,page):
        pattern = re.compile('<div class="year">(.*?)</div>', re.S)
        items = re.findall(pattern, page)
        yearPhotos={}
        for i in range(len(items)):
            yearPhotoList = []
            year = items[i]
            pattern_year = re.compile('<div class="year">'+year+'.*?<ul class="archives.*?<li>.*?<p class="url.*?'+
                                      '<a href="(.*?)".*?>(.*?)</a>', re.S)
            items_year = re.findall(pattern_year,page)
            for item in items_year:
                yearPhotoList.append(item[0],item[1])
                yearPhotos[year] = yearPhotoList
    #获取一个MM列表，0为url地址，1为相册名称
    def getUrlOfYearTest(self,page):
        pattern_year = re.compile('<li>.*?<p class="url.*?<a href="(.*?)".*?>(.*?)</a>', re.S)
        items_year = re.findall(pattern_year, page)
        self.tool.saveText(items_year,'url')
        return items_year
    #获取某一个相册的所有图片
    def getImageOfPhoto(self,url):
        content = self.getPage(url)
        pattern = re.compile('<span>(.*?)</span>', re.S)
        item = re.findall(pattern,content)
        number = item.index(u'\u4e0b\u4e00\u9875&raquo;')
        imageList =[]
        for pg in range(1,int(item[number-1])):
            page_url = url +'/'+str(pg)
            content_page = self.getPage(page_url)
            pattern_photo = re.compile('<div class="main-image.*?<img src="(.*?)"', re.S)
            item = re.findall(pattern_photo, content_page)
            imageList.append(item)
        return imageList
    # 创建新目录
    def mkdir(self, path):
        path = path.strip()
        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists = os.path.exists(path)
        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            print u"偷偷新建了名字叫做", path, u'的文件夹'
            os.chdir(self.dirLocal)
            os.makedirs(path)
            os.chdir(path)
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            print u"名为", path, '的文件夹已经创建过了'
            return False
    # 传入图片地址，文件名，保存单张图片
    def saveImg(self, imageURL, fileName):
        u = urllib.urlopen(imageURL)
        data = u.read()
        f = open(fileName, 'wb')
        f.write(data)
        print u"正在悄悄保存她的一张图片为", fileName
        f.close()
    def download(self,imageURL, fileName):
        urllib.urlretrieve(imageURL, fileName)
    def start(self):
        contents = self.getPage(self.siteUrl)
        photoList = self.getUrlOfYearTest(contents)
        print u'共发现了%d个美女的相册地址' %len(photoList)
        print u'准备读取下载到本地文件夹下'
        count = 1
        for item in photoList[:5]:
            print u'正在读取第',count,u'位美女的相册信息，请稍后。。。。'
            print u'查看当期文件下是否存在相同的文件夹'
            if self.mkdir(item[1]):
                for url in self.getImageOfPhoto(item[0]):
                    name = url[0][self.tool.find_last(url[0],'/')+1:]
                    self.download(url[0],name)
                    count += 1
            else:
                continue


bt = BeautifulGirl()
bt.start()
# bt.saveImg('http://i.meizitu.net/2017/02/17b03.jpg','chen44.png')
# bt.download('http://i.meizitu.net/2017/02/17b03.jpg','chen1.png')

